<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"

    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户">
              <a-select placeholder="选择客户" v-decorator="[ 'supplierId', validatorRules.supplierId ]" :dropdownMatchSelectWidth="false">
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplierId }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :lg="6" :md="12" :sm="24" >
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
              <j-date v-decorator="['operTime']" :show-time="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          @valueChange="onValueChange2"
          @added="onAdded"
          @deleted="onDeleted" />
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { BillModalMixin } from '../../bill/mixins/BillModalMixin'
  import { getMpListShort } from "@/utils/util"
  import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
  import JDate from '@/components/jeecg/JDate'
  import { addEngineeringDepot } from '@/api/api'
  import Vue from 'vue'
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import { VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'

  export default {
    name: "detailsListModal",
    mixins: [JEditableTableMixin, BillModalMixin],
    components: {
      JDate,
      JSelectMultiple,
      JEditableTable
    },
    inject:["reload"],
    props: ['id'],
    data () {
      return {
        title:"操作",
        width: '1450px',
        moreStatus: false,
        arrList:'',
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        operTimeStr: '',
        prefixNo: 'XSDD',
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable', ],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: '仓库名称', key: 'depotId', width: '8%', type: FormTypes.select, placeholder: '请选择${title}', options: [] },
            { title: '条码', key: 'barCode', width: '5%', type: FormTypes.popupJsh },
            { title: '名称', key: 'name', width: '5%', type: FormTypes.input, readonly: true },
            {  title: '商品ID',key: 'ids', width: '5%', type: FormTypes.input, readonly: true },
            { title: '规格', key: 'standard', width: '5%', type: FormTypes.input, readonly: true },
            { title: '型号', key: 'model', width: '5%', type: FormTypes.input, readonly: true },
            { title: '扩展信息', key: 'materialOther', width: '6%', type: FormTypes.input, readonly: true },
            { title: '库存', key: 'stock', width: '5%', type: FormTypes.input, readonly: true },
            { title: '单位', key: 'unit', width: '4%', type: FormTypes.input, readonly: true },
            { title: '数量', key: 'operNumber', width: '5%', type: FormTypes.inputNumber, statistics: true },
            // { title: '单价', key: 'unitPrice', width: '5%', type: FormTypes.inputNumber},
            // { title: '金额', key: 'allPrice', width: '5%', type: FormTypes.inputNumber, statistics: true },
            { title: '零售单价', key: 'commodityDecimal', width: '6%', type: FormTypes.inputNumber, statistics: true },
            { title: '零售金额', key: 'commodityPrice', width: '6%', type: FormTypes.inputNumber, statistics: true },
            { title: '税率', key: 'taxRateCommodity', width: '6%', type: FormTypes.inputNumber, statistics: true },
            { title: '税额', key: 'taxRateCommodityMoney', width: '6%', type: FormTypes.inputNumber, statistics: true },
            { title: '含税单价', key: 'taxRateCommodityDecimal', width: '6%', type: FormTypes.inputNumber, statistics: true },
            { title: '价税合计', key: 'commodityDecimalTotal', width: '6%', type: FormTypes.inputNumber, statistics: true },


            {  key: 'basicNumber', width: '0', type: FormTypes.input, readonly: true },
            {  key: 'billNo', width: '0', type: FormTypes.input, readonly: true },
            {  key: 'createUser', width: '0', type: FormTypes.input, readonly: true },
            // {  key: 'commodityDecimalTotal', width: '0', type: FormTypes.input, readonly: true },
            {  key: 'materialExtendIds', width: '0', type: FormTypes.input, readonly: true },
            {  key: 'materialId', width: '0', type: FormTypes.input, readonly: true },
            {  key: 'materialType', width: '0', type: FormTypes.input, readonly: true },
            { key: 'materialUnit', width: '0', type: FormTypes.input, readonly: true },
          ]
        },
        confirmLoading: false,
        validatorRules:{
          // operTime:{
          //   rules: [
          //     { required: true, message: '请输入单据日期!' }
          //   ]
          // },
          supplierId:{
            rules: [
              { required: true, message: '请选择客户!' }
            ]
          }
        },
        url: {
          // add: '/depotHead/addDepotHeadAndDetail',
          add: '/engineering/addEngineeringDepot',
          edit: '/depotHead/updateDepotHeadAndDetail',
          detailList: '/depotItem/getDetailList'
        }
      }
    },
    created () {
      // this.addList()
    },
    methods: {
      // addList(){
      //   addEngineeringDepot({
      //      "detailArr":engineeringDepot,
      //       "engineeringId":engineeringId
      //   }).then((res) =>{
          
      //     console.log(res,888888)
      //   })
      // },
      //调用完edit()方法之后会自动调用此方法
      add () {
       this.edit({});
      },
      edit (record) {
        console.log('edit',record)
        this.form.resetFields();
        this.visible = true;
        this.confirmLoading =false;
        this.materialTable.dataSource =[];

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },

      editAfter() {
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.personList.value = ''
        } else {
          this.model.operTime = this.model.operTimeStr
          this.personList.value = this.model.salesMan
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'operTime', 'number',
              'discount','discountMoney','discountLastMoney','otherMoney','accountId','changeAmount','salesMan',))
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable,);
          
        }
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        console.log("allValues: ",allValues)
        console.log('dataSource: ',this.materialTable.dataSource)

        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let engineeringId = this.id
        let detailArr = allValues.tablesValue[0].values

        billMain.type = '其它'
        billMain.subType = '销售订单'
        billMain.defaultNumber = billMain.number


        var engineeringDepot = [];
        /*转换表单数据*/
        for(let item of detailArr){
          totalPrice += item.allPrice-0

          const depot = {
            "materialId": item.ids,
            "materialExtendId": item.materialExtendIds,
            "materialUnit": item.unit,
            "operNumber": item.operNumber,
            "basicNumber": 12,
            /*单价*/
            "commodityDecimal": item.commodityDecimal,
            /*总价*/
            "commodityPrice": item.commodityPrice,
            /*税率*/
            "taxRateCommodity": item.taxRateCommodity,
            /*税额*/
            "taxRateCommodityMoney": item.taxRateCommodity,
            /*含税单价*/
            "taxRateCommodityDecimal": item.taxRateCommodityDecimal,
            /*价税合计*/
            "commodityDecimalTotal": item.commodityDecimalTotal,
            // "materialType": "类型"
          }

          engineeringDepot.push(depot)
        }
        billMain.totalPrice = totalPrice
        if(this.model.id){
          billMain.id = this.model.id

        }

        console.log('his.model.id',this.model.id)
        billMain.salesMan = this.personList.value
        console.log(detailArr,555)
        console.log(this.arrList,99)
          return {
            "detailArr":engineeringDepot,
            "engineeringId":engineeringId
          // info: JSON.stringify(billMain),
          // rows: JSON.stringify(detailArr),
        }
        this.visible = false

      },

      handleOk () {
        /** 触发表单验证 */
        let that = this;
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)


          let obj =  addEngineeringDepot(formData);

          obj.then((res)=>{
            if(res.code === 0){
              // that.$emit('成功');
              that.$message.success('成功');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
           // that.confirmLoading = false;
            that.close();
            //  this.reload();

          })

        }).catch(e => {

            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]

            console.error(e)

        })
      },
      handleCancel () {
       // that.confirmLoading = false;
        this.close()
      },

    }
  }
</script>
<style scoped>

</style>